/**
 * File : UDPClient.java Author : R. Scheurer (EIA-FR) Date : 04.10.2012
 *
 * Description - a simple UDP client
 *
 */
package sockets.udp;

import java.net.*;
import java.util.logging.Level;
import java.util.logging.Logger;

// A class that implements the UDP client's behaviour and
// interfaces the provided GUI
public class UDPClient {

    private static final int DEFAULT_PORT = 1324; // The default port to use
    DatagramSocket ds; // The client's datagram socket
    DatagramPacket dp; // The datagram packet to be sent

    // The class' constructor taking in one parameter :
    // - the port that will be used sending the UDP packet
    UDPClient(int LOCALPORT) throws SocketException {
        ds = new DatagramSocket(DEFAULT_PORT);
    }

    // A method called to send the message in an UDP packet
    public void sendMsg(InetSocketAddress isaServer, String msg)
            throws Exception {
        byte[] buffer = new byte[msg.length()];
        buffer = msg.getBytes();
        // We create the packet with all the content we want
        // We do not check max message size as it may sent it to other servers. 
        DatagramPacket datagramPacket = new DatagramPacket(buffer,
                buffer.length, isaServer.getAddress(), isaServer.getPort());
        // We send the created packet
        ds.send(datagramPacket);

        // We display the message that is being sent in the client console.
        // (Good for logging messages)
        String message = "";
        for (byte b : buffer) {
            message += (char) b;
        }
        System.out.println("Sendind message :  " + message);
    }
    
    // A method to close the UDP socket
    public void closeSocket() {
        ds.close();
    }
    
    // A method to return get a correct string containing the port number
    String getPort() {
        String s = "";
        s += DEFAULT_PORT;
        return s;
    }
}
